package com.nineclock.system.service.impl;

import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.config.HxImManager;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper userMapper;
    @Autowired
    SmsService smsService;
    @Autowired
    HxImManager hxImManager;

    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {
        //1. 健壮性的判断
        if (sysRegisterDTO == null || sysRegisterDTO.getMobile()==null || sysRegisterDTO.getCheckcode()==null || sysRegisterDTO.getPassword()==null) {
            throw  new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //2.校验验证码
        Boolean flag = smsService.verify(
                sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER, sysRegisterDTO.getCheckcode());
        if (!flag) {
                throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }

        //3.注册账户
        SysUser user = new SysUser();
        //保存加密后的密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(sysRegisterDTO.getPassword()));
        user.setCreateTime(new Date());
        user.setMobile(sysRegisterDTO.getMobile());
        user.setStatus((short)1);


        userMapper.insert(user);

        //注册用户到数据库完成后,注册用户到环信云
        SysUser user1 = new SysUser();
        user1.setUsername(user.getMobile());
        user1.setPassword("123456");

        hxImManager.registerUser2HuanXing(user1);

        return user.getId();
    }
}
